package aar.test.tessocr.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.CustomFooterViewCallBack;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import aar.test.tessocr.OpenCabActivity;
import aar.test.tessocr.adapter.OrderListAdapter;
import aar.test.tessocr.baseApplication.BaseApplication;
import aar.test.tessocr.model.DialogCallback;
import aar.test.tessocr.model.LzyResponse;
import aar.test.tessocr.model.UnexporderListModel;
import aar.test.tessocr.utils.ConstantPara;
import aar.test.tessocr.utils.PrefUtils;
import aar.test.tessocr.utils.ScreenUtil;
import aar.test.tessocr.utils.Urls;
import aar.test.tessocr.view.CustomDialog;
import aar.test.tessocr.view.CustomLoadingMoreFooter;
import butterknife.BindView;
import clx.tessocr.ocreng.R;
import okgo.OkGo;
import okgo.callback.StringCallback;
import okgo.model.Response;
import okhttp3.RequestBody;

import static aar.test.tessocr.Login1Activity.JSON;

/**
 * 未取件列表
 * Created by sunshine on 2020/9/18
 */
public class OrderUnPickUpFragment extends BaseFragment implements XRecyclerView.LoadingListener{
    @BindView(R.id.rvData)
    XRecyclerView rvData;
    @BindView(R.id.ll_empty)
    LinearLayout imgEmpty;

    private List<UnexporderListModel> mList = new ArrayList<>();
    private OrderListAdapter mAdapter;
    private boolean isFirst = true;
    private int pageNum = 1;
    private String search = "";
    private CustomDialog commitDialog;
    private EditText et_phone;
    private ImageView btn_confirm;

    public static OrderUnPickUpFragment newInstance(String orderType, String search) {
        OrderUnPickUpFragment fragment = new OrderUnPickUpFragment();
        Bundle bundle = new Bundle();
        bundle.putString("orderType", orderType);
        bundle.putString("search", search);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setUpContentView() {
        setContentView(R.layout.fragment_order_delivered);
    }

    @Override
    protected void setUpView(View view) {

    }

    @Override
    protected void setUpComponent() {
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        rvData.setLayoutManager(manager);
        mAdapter = new OrderListAdapter(getActivity(), mList);
        rvData.setAdapter(mAdapter);
        final CustomLoadingMoreFooter footer = new CustomLoadingMoreFooter(getActivity());
        rvData.setFootView(footer, new CustomFooterViewCallBack() {
            @Override
            public void onLoadingMore(View yourFooterView) {
                footer.onLoadingMore();
            }

            @Override
            public void onLoadMoreComplete(View yourFooterView) {
                footer.onLoadMoreComplete();
            }

            @Override
            public void onSetNoMore(View yourFooterView, boolean noMore) {
                footer.onSetNoMore();
            }
        });
        rvData.setPullRefreshEnabled(true);
        rvData.setLoadingMoreEnabled(true);
        rvData.setLoadingListener(this);
    }

    @Override
    protected void setUpData() {

    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        getData();
    }

    @Override
    public void onLoadMore() {
        getData();
    }

    @Override
    public void onResume() {
        super.onResume();
        //recruitType = getArguments().getInt(Constants.RECRUIT_TYPE);
        search = getArguments().getString("search");

        if (isFirst) {
            isFirst = false;
            refreshData();
        }
    }

    private void refreshData() {
        pageNum = 1;
        getData();
    }

    private void getData() {

        final Map<String, Object> map = new HashMap<>();
        map.put("adminid", PrefUtils.getString(getActivity(), "userId", ""));
        map.put("keyword", search);
        map.put("status", "3");
        map.put("page", pageNum);
        map.put("size", ConstantPara.PAGESIZE);


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<LzyResponse<List<UnexporderListModel>>>post(Urls.URL_EXPORDER_LIST)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new DialogCallback<LzyResponse<List<UnexporderListModel>>>(getActivity()) {
                    @Override
                    public void onSuccess(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        Log.e("OrderListActivity","UnDeliveredonSuccess--------------------"+response.body().data.toString());
                        if (pageNum == 1) {
                            mList.clear();
                        }

                        mList.addAll(response.body().data);
                        if (null == mList || mList.size() == 0) {
                            imgEmpty.setVisibility(View.VISIBLE);
                        } else {
                            imgEmpty.setVisibility(View.GONE);
                        }

                        if (null == response.body().data || response.body().data.size() == 0) {
                            rvData.refreshComplete();
                            rvData.loadMoreComplete();
                            rvData.setNoMore(true);

                            return;
                        } else {
                            if (null != response.body().data && response.body().data.size() > 0) {
                                rvData.refreshComplete();
                                pageNum++;

                                mAdapter.notifyDataSetChanged();

                                mAdapter.setViewClickListener(new OrderListAdapter.ViewClickListener() {
                                    @Override
                                    public void post_again(int pos) {
                                    }

                                    @Override
                                    public void gridTackBack(int pos) {
                                        expordergridGiveBack(pos);
                                        expordergridOpen(pos);
                                    }

                                    @Override
                                    public void modify_phone(int pos) {
                                        modifyPhone(pos);
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Response<LzyResponse<List<UnexporderListModel>>> response) {
                        if (pageNum == 1) {
                            imgEmpty.setVisibility(View.VISIBLE);
                            mList.clear();
                            mAdapter.notifyDataSetChanged();
                        }
                        rvData.refreshComplete();
                        rvData.loadMoreComplete();
                        rvData.setNoMore(true);

                    }
                });
    }

    private void modifyPhone(int pos) {
        showReturnOrderIdDialog(pos);
    }

    private void showReturnOrderIdDialog(int pos) {
        View view = View.inflate(getActivity(), R.layout.dialog_modify_phone, null);
        initregisterDialogView(view, pos);
        commitDialog = new CustomDialog(getActivity(), ScreenUtil.dp2px(getActivity(), 270), ScreenUtil.dp2px(getActivity(), 300),
                view, R.style.CustomDialog);
        commitDialog.show();
    }

    private void initregisterDialogView(View view, final int pos) {
        Button btnConfirmDelete = view.findViewById(R.id.btn_dialog_register_activity_submit);
        et_phone = view.findViewById(R.id.et_phone);
        btn_confirm = view.findViewById(R.id.img_cancel);

        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closeDialog();
            }
        });

        btnConfirmDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (et_phone.getText().toString().trim().equals("")) {
                    Toast.makeText(getActivity(), "请输入手机号码", Toast.LENGTH_SHORT).show();
                    return;
                }

                Map<String, Object> map = new HashMap<>();
                map.put("orderid", mList.get(pos).getId());
                map.put("phone",et_phone.getText().toString().trim());

                Gson gg = new Gson();
                String json = gg.toJson(map);

                RequestBody body = RequestBody.create(JSON, json);
                OkGo.<String>post(Urls.URL_EDIT_PHONE)//
                        .tag(this)//
                        .upRequestBody(body)
                        .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {

                                Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                                try {
                                    JSONObject jsonObject = new JSONObject(response.body());
                                    if (jsonObject.has("code")) {
                                        String code = jsonObject.getString("code");
                                        if (TextUtils.equals(code, "200")) {
                                            String msg = jsonObject.getString("msg");
                                            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                        } else if (TextUtils.equals(code, "100")) {
                                            String msg = jsonObject.getString("msg");
                                            Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                                            mList.get(pos).setPhone(et_phone.getText().toString().trim());
                                            mAdapter.notifyDataSetChanged();
                                            closeDialog();
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }

                            }
                        });
            }
        });
    }

    private void closeDialog() {
        if (commitDialog != null && commitDialog.isShowing()) {
            commitDialog.dismiss();
        }
    }

    private void expordergridGiveBack(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("orderid", mList.get(pos).getId());


        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_GIVE_BACK)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        Log.e("SiteDispatchActivity", "onSuccess-----logout---------------" + response.body());
                        try {
                            JSONObject jsonObject = new JSONObject(response.body());
                            if (jsonObject.has("code")) {
                                String code = jsonObject.getString("code");
                                if (TextUtils.equals(code, "200")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
                                }else if (TextUtils.equals(code, "100")) {
                                    String msg=jsonObject.getString("msg");
                                    Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
                                    pageNum = 1;
                                    getData();
                                }
                            }


                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });


    }

    private void expordergridOpen(int pos) {


        Map<String, Object> map = new HashMap<>();
        map.put("cabinetId", mList.get(pos).getCabinetid());
        map.put("type", "0");
        map.put("cabinetGridId", mList.get(pos).getCabinetgridid());
        map.put("adminid", PrefUtils.getString(getActivity(), "userId", ""));

        Gson gg = new Gson();
        String json = gg.toJson(map);

        RequestBody body = RequestBody.create(JSON, json);
        OkGo.<String>post(Urls.URL_EXPUSEROPEN)//
                .tag(this)//
                .upRequestBody(body)
                .isMultipart(false)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                             @Override
                             public void onSuccess(Response<String> response) {

                             }

                             @Override
                             public void onError(Response<String> response) {
                                 Log.e("MainActivity", "onError---------------------");

                             }
                         }

                );


    }
}
